package com.lib.common.view;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;

import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.lib.common.R;

import java.util.List;

public class ViewPagerDialog extends Dialog {
    private ViewPager mViewPager;

    /**
     * @param context 上下文
     * @param views   要显示的View的集合
     */
    public ViewPagerDialog(Context context, List<View> views) {
        super(context, R.style.PopFadedAnimStyle);
        mViewPager = new ViewPager(getContext());
        mViewPager.setPageMargin(20);
        mViewPager.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        mViewPager.setBackgroundColor(Color.GRAY);
        mViewPager.setClipChildren(false);
        setContentView(mViewPager);
        setFullScreenParams();

        mViewPager.setAdapter(new ViewPagerAdapter(views));
    }

    private void setFullScreenParams() {

        LayoutParams params = getWindow().getAttributes();
        DisplayMetrics dm = getContext().getResources().getDisplayMetrics();
        Rect rect = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        params.height = dm.heightPixels - rect.top;
        params.width = dm.widthPixels;
    }

    public void setMarginPixels(int marginPixels) {

        if (mViewPager != null) {
            mViewPager.setPageMargin(marginPixels);
        }
    }

    /**
     * @param position 要显示第几页的ViewPager
     */
    public void show(int position) {

        if (mViewPager != null) {
            mViewPager.setCurrentItem(position);
        }
        super.show();
    }

    private static class ViewPagerAdapter extends PagerAdapter {

        private List<View> mViews;

        ViewPagerAdapter(List<View> views) {

            mViews = views;
        }

        @Override
        public int getCount() {

            return mViews == null ? 0 : mViews.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {

            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            View view = mViews.get(position);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {

            container.removeView((View) object);
        }
    }
}
